//获取基础域名：比如baidu.com
export const getBaseUrl = () => {
  const currentHost = window.location.host;
  return `${currentHost}`;
};

//组装一个静态文件
//addTimestamp：是否加上时间戳(动态刷新用)
export const formatStaticUrl = (staticPath: string, addTimestamp = true) => {
  if (!staticPath) {
    return "";
  }
  let baseUrl = getBaseUrl();
  staticPath = removePrefix(staticPath);//删除 ./前缀
  var timestamp = Date.now(); // 获取当前时间的毫秒数
  let url = `//${baseUrl}/${staticPath}`;
  if (addTimestamp) {
    url = url + "?" + timestamp;
  }
  return url;
};

//删除静态文件前缀
function removePrefix(str: string) {
  try {
    if (str.startsWith("./")) {
      return str.substring(2);
    } else if (str.startsWith("/")) {
      return str.substring(1);
    } else {
      return str;
    }
  } catch (e) {
    console.log(str, " ---str");
    console.log(e, " ---e");
    return "";
  }
  return "";
}

// 测试示例
// console.log(removePrefix("./example.txt")); // 输出 "example.txt"
// console.log(removePrefix("/example.txt")); // 输出 "example.txt"
// console.log(removePrefix("example.txt"));  // 输出 "example.txt"
